<template>
  <el-dialog title="自定义统计事项" v-model="visible" :append-to-body="true" width="800px">
    <el-button size="small" type="primary" style="margin-bottom: 5px" :icon="Plus" @click="openForm(null)">添加</el-button>
    <el-table :data="matterList" size="small" stripe border :header-cell-style="{textAlign: 'center', background: 'var(--el-color-primary-light-9)', color: 'var(--next-bg-menuBar-light-1)'}" :cell-style="{textAlign: 'center'}">
      <el-table-column label="事项" prop="name"/>
      <el-table-column label="排序" prop="sort"/>
      <el-table-column label="添加时间" prop="createTime"/>
      <el-table-column label="操作" width="120">
        <template v-slot="{row}">
          <el-button size="small" type="primary" text :icon="Edit" @click="openForm(row)"/>
          <el-button size="small" type="danger" text :icon="Delete" @click="removeMatter(row)"/>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="formData.id ? '编辑' : '添加'" v-model="formVisible" :append-to-body="true" width="600px">
      <el-form :model="formData" :rules="rules" label-width="100px" size="small" ref="formRef">
        <el-form-item label="事项" prop="code">
          <el-select v-model="selectedMatter" placeholder="请选择事项" clearable value-key="code" filterable @change="matterChange">
            <el-option v-for="item in matterItems" :key="item.code" :label="item.name" :value="item"/>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :controls="false" :min="-99999" :max="99999"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="small" @click="formVisible = false">关闭</el-button>
        <el-button size="small" type="primary" @click="submitData(formRef)">保存</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <el-button size="small" type="primary" @click="visible = false">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {computed, reactive, ref, toRefs} from 'vue'
import {Edit, Delete, Plus} from '@element-plus/icons-vue'
import {getModuleMatters} from '/@/api/matter'
import customerMatterApi from '/@/api/ums/customer/matter'
import {ElMessage, ElMessageBox} from 'element-plus'

export default {
  name: 'MatterSetting',
  emits: ['callback', 'update:dialogVisible'],
  props: {
    matterList: {
      type: Array,
      default: []
    },
    dialogVisible: {
      type: Boolean,
      default: false
    }
  },
  setup(props, context) {
    const formRef = ref()
    const {dialogVisible} = toRefs(props)
    let visible = computed({
      get: () => {
        if (dialogVisible.value) {
          getModuleMatters('Customer').then(res => state.matterItems = res.data).catch(e => console.log(e))
        }
        return dialogVisible.value
      },
      set: (val) => context.emit('update:dialogVisible', val)
    })

    const state = reactive({
      formData: {
        id: null,
        code: null,
        name: null,
        sort: 0
      },
      rules: {
        code: {required: true, message: '请选择要统计事项', trigger: 'change'}
      },
      formVisible: false,
      matterItems: [],
      selectedMatter: null
    })

    // 打开表单
    const openForm = (item) => {
      if (item && item.id) {
        state.formData = JSON.parse(JSON.stringify(item))
        state.selectedMatter = {
          code: state.formData.code,
          name: state.formData.name
        }
      } else {
        state.formData = {
          id: null,
          code: null,
          name: null,
          sort: 0
        }
        state.selectedMatter = null
      }
      state.formVisible = true
    }
    // 添加/编辑
    const submitData = (formEl) => {
      formEl.validate(async (valid) => {
        if (!valid) {
          return
        }
        let res
        if (state.formData.id) {
          res = await customerMatterApi.edit(state.formData)
        } else {
          res = await customerMatterApi.create(state.formData)
        }
        if (res.data) {
          ElMessage.success('保存成功！')
          context.emit('callback')
          state.formVisible = false
        }
      })
    }
    // 移除
    const removeMatter = (item) => {
      ElMessageBox.confirm(`确定移除 “${item.name}”？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        buttonSize: 'small',
        type: 'warning'
      }).then(() => {
        customerMatterApi.remove(item).then(res => {
          if (res.data) {
            ElMessage.success('删除成功！')
            context.emit('callback')
          }
        })
      }).catch(() => {
      })
    }
    const matterChange = (matterItem) => {
      if (matterItem) {
        state.formData.code = matterItem.code
        state.formData.name = matterItem.name
      } else {
        state.formData.code = state.formData.name = null
      }
    }

    return {
      Edit,
      Plus,
      Delete,
      formRef,
      ...toRefs(state),
      visible,
      openForm,
      submitData,
      removeMatter,
      matterChange
    }
  }
}
</script>

<style scoped lang="scss">
</style>
